<template>
  <el-dialog
    title="规则配置"
    :model-value="visible"
    @update:model-value="$emit('update:visible', $event)"
    width="800px"
    append-to-body
    class="rule-config-modal"
  >
    <!-- AI 模型选择 (全局配置) -->
    <el-form label-width="100px" label-position="left" @submit.prevent>
      <el-form-item label="AI 模型:">
        <el-select
          v-model="selectedAiModelId"
          placeholder="请选择 AI 模型"
          clearable
          filterable
          style="width: 100%;"
          :loading="isLoadingModels"
        >
          <el-option
            v-for="model in aiModelOptions"
            :key="model.id"
            :label="model.name" 
            :value="model.id!"
          />
        </el-select>
      </el-form-item>
    </el-form>

    <!-- 规则列表与新增表单切换 -->
    <el-tabs v-model="activeTab">
      <el-tab-pane label="规则列表" name="list">
        <!-- 搜索区域 -->
        <el-form :inline="true" class="search-form">
          <el-form-item label="职位名称">
            <el-input v-model="queryParams.jobName" placeholder="请输入职位名称" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">搜索</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <!-- 规则列表表格 -->
        <el-table v-loading="tableLoading" :data="ruleList" style="width: 100%">
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="jobName" label="职位类型" width="150" />
          <el-table-column prop="aiName" label="AI模型" width="150" />
          <el-table-column prop="prompt" label="提示词" show-overflow-tooltip />
          <el-table-column prop="threshold" label="分数阈值" width="80" />
          <el-table-column label="操作" width="120" align="center">
            <template #default="scope">
              <el-button type="text" size="small" class="delete-btn" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页控件 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="queryParams.pageNo"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-tab-pane>
      
      <el-tab-pane label="新增规则" name="create">
        <!-- 全局新增规则按钮 -->
        <div style="margin-bottom: 15px; text-align: right;">
          <el-button type="primary" @click="addRule" :disabled="rules.length >= 5">新增规则</el-button> <!-- 最多5条规则示例 -->
        </div>

        <!-- 规则块列表 -->
        <div v-if="rules.length === 0" style="text-align: center; color: #909399; padding: 20px; border: 1px dashed #dcdfe6; border-radius: 4px;">
          暂无规则，请点击上方"新增规则"按钮添加。
        </div>

        <div v-for="(rule, index) in rules" :key="rule.id" class="rule-block">
          <div class="rule-actions-header">
            <el-text type="primary" tag="b" style="margin-right: auto;">规则 {{ index + 1 }}</el-text>
            <el-link type="danger" @click="deleteRule(index)">删除此规则</el-link>
          </div>
          <el-form :model="rule" label-width="100px" label-position="left" @submit.prevent>
            <el-form-item label="职位类型:">
              <el-select v-model="rule.jobName" placeholder="请选择职位类型" style="width: 100%;" clearable filterable>
                <el-option v-for="item in programmerPositionOptions" :key="item.value" :label="item.label" :value="item.label" />
              </el-select>
            </el-form-item>
            <el-form-item label="提示词:">
              <el-input v-model="rule.prompt" type="textarea" :rows="3" placeholder="请输入提示词" />
            </el-form-item>
            <el-form-item label="分数阈值:">
              <div class="threshold-input-container">
                <span class="threshold-prefix">大于等于</span>
                <el-input-number v-model="rule.threshold" :min="0" :max="100" controls-position="right" placeholder="阈值" class="threshold-input" />
                <span class="threshold-suffix">分</span>
                <span class="threshold-tip">(分数预设100分)</span>
              </div>
            </el-form-item>
            <div style="text-align: right; margin-top: 10px;">
              <el-button type="primary" @click="saveRule(rule)" :loading="rule.isSaving">保存规则</el-button>
            </div>
          </el-form>
          <el-divider v-if="rules.length > 1 && index < rules.length - 1" style="margin-top: 20px;" />
        </div>
      </el-tab-pane>
    </el-tabs>
    
    <template #footer>
      <el-button @click="$emit('update:visible', false)">关 闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus' // 引入 ElMessageBox
import { ModelApi, type ModelVO } from '@/api/ai/model/model'
import { PersonnelResumeApi } from '@/api/hrm/personnelresume'
import request from '@/config/axios'

// props 定义
const props = defineProps<{
  visible: boolean
}>()

// emits 定义
const emit = defineEmits<{
  (e: 'update:visible', visible: boolean): void
  (e: 'submit', data: { aiModelId: ModelVO['id'] | null; rules: RuleData[] }): void;
}>()

// --- AI 模型选择逻辑 ---
const DEFAULT_MODEL_ID = 'YOUR_DEFAULT_MODEL_ID_HERE'; 
const aiModelOptions = ref<ModelVO[]>([])
const selectedAiModelId = ref<string | null>(null);
const isLoadingModels = ref(false)

// Tab页切换
const activeTab = ref('list')

// --- 表单数据定义 ---
interface RuleData {
  id: string; // 为每个规则添加唯一ID，方便key管理和可能的后端交互
  jobName: string | null 
  prompt: string
  threshold: number
  isSaving?: boolean // 保存中状态
}

const rules = ref<RuleData[]>([])

// 程序员职位选项
const programmerPositionOptions = ref([
  { label: '前端工程师', value: 'frontend' },
  { label: '后端工程师', value: 'backend' },
  { label: '全栈工程师', value: 'fullstack' },
  { label: '全栈开发', value: 'fullstack' },
  { label: '移动端工程师', value: 'mobile' },
  { label: 'DevOps工程师', value: 'devops' },
  { label: '数据工程师', value: 'data' },
  { label: '测试工程师', value: 'test' },
  { label: '系统架构师', value: 'architect' }
])

const fetchAiModels = async () => {
  isLoadingModels.value = true
  try {
    const data = await ModelApi.getModelSimpleList(1)
    aiModelOptions.value = data || []

    if (aiModelOptions.value.length > 0) {
      const defaultModelExists = aiModelOptions.value.some(model => String(model.id) === DEFAULT_MODEL_ID)
      if (defaultModelExists) {
        selectedAiModelId.value = DEFAULT_MODEL_ID
      } else {
        selectedAiModelId.value = aiModelOptions.value[0].id
        if (DEFAULT_MODEL_ID !== 'YOUR_DEFAULT_MODEL_ID_HERE') {
            console.warn(
            `[RuleConfigModal] Default AI model ID '${DEFAULT_MODEL_ID}' not found. Selecting first available: '${selectedAiModelId.value}'.`
          )
        }
      }
    } else {
      selectedAiModelId.value = null
    }
  } catch (error) {
    console.error("[RuleConfigModal] Failed to fetch AI models:", error)
    ElMessage.error('获取AI模型列表失败')
    aiModelOptions.value = []
    selectedAiModelId.value = null
  } finally {
    isLoadingModels.value = false
  }
}

// --- 操作方法 ---
const createNewRule = (): RuleData => ({
  id: Date.now().toString() + Math.random().toString(36).substring(2, 9), // 简易唯一ID
  jobName: null,
  prompt: '',
  threshold: 0, // 初始化为0而不是null
  isSaving: false
});

const addRule = () => {
  if (rules.value.length >= 5) { // 限制规则数量
    ElMessage.warning('最多只能添加5条规则');
    return;
  }
  rules.value.push(createNewRule());
  ElMessage.success('新规则已添加');
}

// 保存单个规则
const saveRule = async (rule: RuleData) => {
  // 验证规则数据
  if (!selectedAiModelId.value) {
    ElMessage.warning('请先选择AI模型');
    return;
  }
  
  if (!rule.jobName) {
    ElMessage.warning('请选择职位类型');
    return;
  }
  
  if (!rule.prompt) {
    ElMessage.warning('请输入提示词');
    return;
  }
  
  // 开始保存
  rule.isSaving = true;
  try {
    // 调用API创建规则
    await request.post({ 
      url: '/hrm/personnel-ai-rule/create', 
      data: {
        aiModelId: Number(selectedAiModelId.value),
        jobName: rule.jobName,
        prompt: rule.prompt,
        threshold: rule.threshold
      }
    });
    ElMessage.success('规则保存成功');
    
    // 保存成功后切换到规则列表，并刷新
    activeTab.value = 'list'
    fetchRuleList()
    
    // 清空表单
    rules.value = []
  } catch (error) {
    console.error('[RuleConfigModal] Failed to save rule:', error);
    ElMessage.error('规则保存失败，请重试');
  } finally {
    rule.isSaving = false;
  }
}

const deleteRule = (index: number) => {
  ElMessageBox.confirm(
    `确定要删除规则 ${index + 1} 吗？此操作不可撤销。`,
    '警告',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    rules.value.splice(index, 1);
    ElMessage.success(`规则 ${index + 1} 已删除`);
  }).catch(() => {
    // 用户取消删除
    ElMessage.info('已取消删除操作');
  });
}

const submitForm = () => {
  if (rules.value.length === 0) {
    ElMessage.warning('请至少配置一条规则');
    return;
  }

  const submissionData = {
    aiModelId: selectedAiModelId.value,
    rules: rules.value.map(({ id, jobName, prompt, threshold }) => ({ 
      id, jobName, prompt, threshold
    }))
  };
  console.log('提交的规则数据:', submissionData);
  emit('submit', submissionData);
  ElMessage.success('规则配置已提交');
  emit('update:visible', false) // 关闭弹窗
}

watch(() => props.visible, (newVal) => {
  if (newVal) {
    // 每次打开弹窗时加载分页数据
    fetchRuleList()
    
    // 加载AI模型列表
    if (aiModelOptions.value.length === 0) {
      fetchAiModels();
    }
    
    // 弹窗打开时，如果规则列表为空，则自动添加一条默认规则(针对新增tab)
    if (rules.value.length === 0) {
      rules.value.push(createNewRule());
    }
  }
}, { immediate: false });

// 组件挂载时初始化
onMounted(() => {
  if (props.visible) {
    fetchRuleList()
    fetchAiModels()
  }
})

// 表格数据
const tableLoading = ref(false)
const ruleList = ref<any[]>([])
const total = ref(0)
const queryParams = reactive({
  pageNo: 1, 
  pageSize: 10,
  jobName: ''
})

// 获取规则列表
const fetchRuleList = async () => {
  tableLoading.value = true
  try {
    const response = await request.get({ 
      url: '/hrm/personnel-ai-rule/page', 
      params: queryParams 
    })
    ruleList.value = response.list || []
    total.value = response.total || 0
  } catch (error) {
    console.error("[RuleConfigModal] Failed to fetch rule list:", error)
    ElMessage.error('获取规则列表失败')
  } finally {
    tableLoading.value = false
  }
}

// 搜索
const handleQuery = () => {
  queryParams.pageNo = 1
  fetchRuleList()
}

// 重置搜索
const resetQuery = () => {
  queryParams.jobName = ''
  handleQuery()
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  queryParams.pageSize = size
  fetchRuleList()
}

// 页码变化
const handleCurrentChange = (page: number) => {
  queryParams.pageNo = page
  fetchRuleList()
}

// 删除规则
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    `确定要删除职位为"${row.jobName}"的规则吗？此操作不可撤销。`,
    '警告',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      await request.delete({ 
        url: `/hrm/personnel-ai-rule/delete?id=${row.id}`
      })
      ElMessage.success('删除成功')
      fetchRuleList()
    } catch (error) {
      console.error("[RuleConfigModal] Failed to delete rule:", error)
      ElMessage.error('删除规则失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除操作')
  })
}

</script>

<style lang="scss" scoped>
.rule-config-modal {
  .search-form {
    margin-bottom: 15px;
  }
  
  .pagination-container {
    margin-top: 15px;
    text-align: right;
  }
  
  .rule-block {
    padding: 15px;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    margin-bottom: 15px;
    background-color: #fdfdfd; // Slightly lighter background for differentiation

    &:last-child {
      margin-bottom: 0;
    }
  }

  .rule-actions-header {
    display: flex; // Use flexbox for alignment
    justify-content: space-between; // Pushes elements to ends
    align-items: center; // Vertically align items
    margin-bottom: 15px;
  }

  :deep(.el-form-item) {
    margin-bottom: 12px; 
  }
  
  .threshold-input-container {
    display: flex;
    align-items: center;
    flex-wrap: nowrap;
    
    .threshold-prefix {
      margin-right: 8px;
      white-space: nowrap;
    }
    
    .threshold-input {
      width: 120px;
    }
    
    .threshold-suffix {
      margin-left: 8px;
      margin-right: 12px;
    }
    
    .threshold-tip {
      color: #909399;
      font-size: 12px;
    }
  }
  
  .delete-btn {
    color: #f56c6c;
    
    &:hover {
      color: #f89898;
    }
  }
}
</style>
